package com.naiterui.ehp.bs.recommend.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.naiterui.ehp.bp.bo.doctor.DoctorLabelBO;
import com.naiterui.ehp.bp.bo.doctor.RecomUserInfoBO;
import com.naiterui.ehp.bp.bo.recommend.RecomDiagnosisBO;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.utils.lang.ConfigUtil;
import com.naiterui.ehp.bs.recommend.bean.DrCommonPrescription;
import com.naiterui.ehp.bs.recommend.bean.DrCommonPrescriptionDetail;
import com.naiterui.ehp.bs.recommend.exception.ExceptionCodes;
import com.naiterui.ehp.bs.recommend.remote.IRecommendRemoter;
import com.naiterui.ehp.bs.recommend.repository.mysql.IDrCommonPrescriptionDetailRepository;
import com.naiterui.ehp.bs.recommend.repository.mysql.IDrCommonPrescriptionRepository;
import com.naiterui.ehp.bs.recommend.service.IDrCommonPrescriptionService;
import com.naiterui.ehp.bs.recommend.service.IDrDiagnosisService;
import com.naiterui.ehp.bs.recommend.vo.DrCommonPrescriptionDetailVO;
import com.naiterui.ehp.bs.recommend.vo.DrCommonPrescriptionVO;

@Service
public class DrCommonPrescriptionServiceImpl implements IDrCommonPrescriptionService {

    private static final Logger LOGGER = LoggerFactory.getLogger(DrCommonPrescriptionServiceImpl.class);

    private static String RECOM_DELETE_DIAGNOSE_TIP = ConfigUtil.getString("recom.delete.diagnose.tip");
    //表示需要删除非标准诊断
    private static int OPERATIONTYPE_TYPE_DELETE = 2;

    @Autowired
    private IDrCommonPrescriptionRepository drCommonPrescriptionRepository;
    @Autowired
    private IDrCommonPrescriptionDetailRepository drCommonPrescriptionDetailRepository;
    @Autowired
    private IRecommendRemoter remoter;
    @Autowired
    private IDrDiagnosisService diagnosisService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(DrCommonPrescriptionVO commonPrescriptionVo, Long doctorId) throws BusinessException {
        LOGGER.debug("新增常用处方commonPrescriptionVo:[{}]||doctorId:{}", JSON.toJSONString(commonPrescriptionVo), doctorId);
        // 诊断名称
        List<String> diagonsisList = commonPrescriptionVo.getDiagnosis();

        List<DrCommonPrescriptionDetailVO> detailList = commonPrescriptionVo.getPredcriptionDetailList();

        if (diagonsisList.isEmpty() || detailList.isEmpty()) {
            throw new BusinessException(ExceptionCodes.PARAM_ERROR);
        }
        //医生端3.5   保存常用处方拦截非标准诊断  created by wanglin 2018-11-28
        RecomUserInfoBO userInfo = this.remoter.getUserInfo(doctorId, null, true);
        if (null == userInfo || null == userInfo.getDoctor()) {
            throw new BusinessException(ExceptionCodes.DOCTOR_RECOM_EXITS);
        }
        DoctorLabelBO doctorLabelBO = userInfo.getDoctor().getLabel();
        if (doctorLabelBO != null && doctorLabelBO.getDiagnosis()) {
            RecomDiagnosisBO recomDiagnosisBO = this.diagnosisService.getStandardDiagnosis(diagonsisList);
            if (StringUtils.isNotBlank(recomDiagnosisBO.getDiagnoseDeleteTip())) {
                throw new BusinessException(ExceptionCodes.DOCTOR_RECOM_EXIST_CUSTOMER);
            }
        }
        String diagnosis = "";
        if (!diagonsisList.isEmpty()) {
            diagnosis = JSON.toJSONString(diagonsisList);
            // 更新诊断库
            this.diagnosisService.updateCommonDiagnosis(doctorId, diagonsisList);
        }
        // 创建常用处方并赋值
        DrCommonPrescription commonPrescription = new DrCommonPrescription();
        commonPrescription.setCreatedAt(new Date());
        commonPrescription.setChangedAt(new Date());
        commonPrescription.setDoctorId(doctorId);
        commonPrescription.setDiagnosis(diagnosis);
        commonPrescription.setCreatedBy("system");
        commonPrescription.setVersion(0);

        // 保存常用处方，返回处方id
        Long id = this.drCommonPrescriptionRepository.save(commonPrescription).getId();

        if (!detailList.isEmpty()) {
            DrCommonPrescriptionDetail commonPrescriptionDetail = null;
            for (DrCommonPrescriptionDetailVO detailVO : detailList) {
                commonPrescriptionDetail = new DrCommonPrescriptionDetail();
                BeanUtils.copyProperties(detailVO, commonPrescriptionDetail);
                if (detailVO.getSkuId() == null) {
                    commonPrescriptionDetail.setSkuId(0L);
                }
                commonPrescriptionDetail.setPrescriptionId(id);
                commonPrescriptionDetail.setVersion(0);
                commonPrescriptionDetail.setCreatedAt(new Date());
                // 保存常用处方详情
                this.drCommonPrescriptionDetailRepository.save(commonPrescriptionDetail);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DrCommonPrescriptionVO commonPrescriptionVo, Long doctorId) throws BusinessException {
        LOGGER.debug("新增常用处方commonPrescriptionVo:[{}]||doctorId:{}", JSON.toJSONString(commonPrescriptionVo), doctorId);
        Long id = commonPrescriptionVo.getId();
        // 诊断名称
        List<String> diagonsisList = commonPrescriptionVo.getDiagnosis();

        List<DrCommonPrescriptionDetailVO> detailList = commonPrescriptionVo.getPredcriptionDetailList();
        if (diagonsisList.isEmpty() || detailList.isEmpty()) {
            throw new BusinessException(ExceptionCodes.PARAM_ERROR);
        }
        //医生端3.5   保存常用处方拦截非标准诊断  created by wanglin 2018-11-28
        RecomUserInfoBO userInfo = this.remoter.getUserInfo(doctorId, null, true);
        if (null == userInfo || null == userInfo.getDoctor()) {
            throw new BusinessException(ExceptionCodes.DOCTOR_RECOM_EXITS);
        }
        DoctorLabelBO doctorLabelBO = userInfo.getDoctor().getLabel();
        if (doctorLabelBO != null && doctorLabelBO.getDiagnosis()) {
            RecomDiagnosisBO recomDiagnosisBO = this.diagnosisService.getStandardDiagnosis(diagonsisList);
            if (StringUtils.isNotBlank(recomDiagnosisBO.getDiagnoseDeleteTip())) {
                throw new BusinessException(ExceptionCodes.DOCTOR_RECOM_EXIST_CUSTOMER);
            }
        }
        String diagnosis = "";
        if (!diagonsisList.isEmpty()) {
            diagnosis = JSON.toJSONString(diagonsisList);
            // 更新诊断库
            this.diagnosisService.updateCommonDiagnosis(doctorId, diagonsisList);
        }

        DrCommonPrescription prescription = this.drCommonPrescriptionRepository.get(id);
        if (prescription == null) {
            throw new BusinessException(ExceptionCodes.PARAM_ERROR);
        }

        prescription.setChangedAt(new Date());
        prescription.setDiagnosis(diagnosis);
        prescription.setChangedBy("system");
        // 常用处方更新
        this.drCommonPrescriptionRepository.update(prescription);

        // 常用处方详情更新操作
        if (!detailList.isEmpty()) {
            // 获取该处方下所有处方详情id
            List<Long> stockList = new ArrayList<>();
            List<DrCommonPrescriptionDetail> commonList = this.drCommonPrescriptionDetailRepository.findByPrescriptionIdOrderByIdAsc(id);
            for (DrCommonPrescriptionDetail drCommonPrescriptionDetail : commonList) {
                stockList.add(drCommonPrescriptionDetail.getId());
            }

            List<Long> newList = new ArrayList<>();
            for (DrCommonPrescriptionDetailVO detailVO : detailList) {
                Long detailVoId = detailVO.getId();
                if (detailVoId != null) {
                    newList.add(detailVO.getId());
                }
            }

            Collection<?> collection = CollectionUtils.subtract(stockList, newList);

            // 取出需要删除的处方详情id
            // 删除动作
            if (!collection.isEmpty()) {
                for (Object aCollection : collection) {
                    Long tempId = (Long) aCollection;
                    DrCommonPrescriptionDetail detailInfo = this.drCommonPrescriptionDetailRepository.get(tempId);
                    if (detailInfo != null) {
                        this.drCommonPrescriptionDetailRepository.deleteById(tempId);
                    }
                }
            }

            DrCommonPrescriptionDetail commonPrescriptionDetail = null;
            for (DrCommonPrescriptionDetailVO detailVO : detailList) {
                commonPrescriptionDetail = new DrCommonPrescriptionDetail();
                BeanUtils.copyProperties(detailVO, commonPrescriptionDetail);
                Long dId = detailVO.getId();
                // 保存常用处方详情
                if (dId == null || dId == 0) {
                    commonPrescriptionDetail.setPrescriptionId(id);
                    commonPrescriptionDetail.setVersion(0);
                    commonPrescriptionDetail.setCreatedAt(new Date());
                    if (detailVO.getSkuId() == null) {
                        commonPrescriptionDetail.setSkuId(0L);
                    }
                    this.drCommonPrescriptionDetailRepository.save(commonPrescriptionDetail);
                } else {// 否则更新常用处方详情
                    DrCommonPrescriptionDetail detailInfo = this.drCommonPrescriptionDetailRepository.get(dId);
                    if (detailInfo != null) {
                        BeanUtils.copyProperties(detailVO, detailInfo);
                        detailInfo.setChangedAt(new Date());
                        this.drCommonPrescriptionDetailRepository.save(detailInfo);
                    }
                }
            }
        } else {
            this.drCommonPrescriptionDetailRepository.deleteAllByPrescriptionId(id);
        }
    }
}
